package ru.surfstudio.graduate.handler;

import ru.surfstudio.graduate.R;
import ru.surfstudio.graduate.activity.SearchChannelActivity;
import ru.surfstudio.graduate.activity.ChannelResultActivity;
import ru.surfstudio.graduate.service.HttpService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class ChannelResultHandler extends Handler {
	
	private static final String TAG = "ChannelResultHandler";
	
	private SearchChannelActivity activity = null;
	
	public ChannelResultHandler(SearchChannelActivity activity) {
		super();
		attach(activity);
	}
	
	@Override
	public void handleMessage(Message msg) {
		Bundle data = msg.getData();
		
		if (activity != null && data != null) {
			int status = data.getInt(HttpService.MARK_STATUS);
			
			switch (status) {
				case HttpService.STATUS_RUNNING:
					activity.showDialog(SearchChannelActivity.DIALOG_SEARCH);
					break;
	
				case HttpService.STATUS_FINISHED:
					activity.dismissDialog(SearchChannelActivity.DIALOG_SEARCH);
					
					Intent intent = new Intent(activity, ChannelResultActivity.class);
					intent.putExtra(ChannelResultActivity.MARK_CHANNEL_LIST, 
							data.getSerializable(HttpService.MARK_RESPONSE));
					intent.putExtra(ChannelResultActivity.MARK_SEARCH_TEXT, activity.getSearchTextStr());
					activity.startActivity(intent);
					break;
					
				case HttpService.STATUS_ERROR:
					activity.dismissDialog(SearchChannelActivity.DIALOG_SEARCH);
					Toast.makeText(activity, R.string.channel_result_load_error, Toast.LENGTH_LONG)
						.show();
					Log.w(TAG, activity.getString(R.string.channel_result_load_error));
					break;
			}
		}
	}
	
	
	public void attach(SearchChannelActivity activity) {
		this.activity = activity;
	}
	
	public void detach() {
		activity = null;
	}
	
}
